//
//  HLLoginCodeViewController.m
//  YueYue
//
//  Created by hulu001 on 2023/5/20.
//

#import "HLLoginCodeViewController.h"
#import "HLLoginOptionRequest.h"
#import "HLLoginAgreeProtocolView.h"

@interface HLLoginCodeViewController ()<QMUITextFieldDelegate>

@property (nonatomic, strong) UIImageView *headerView;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UILabel *detailLabel;
@property (nonatomic, strong) NSString *loginPhoneKey;
@property (nonatomic, strong) QMUITextField *textField;
@property (nonatomic, strong) QMUITextField *codeField;
@property (nonatomic, strong) QMUIButton *saveButton;
@property (nonatomic, strong) QMUIButton *codeButton;
@property (nonatomic, weak) NSTimer *countdownTimer;

@property (nonatomic, strong) HLLoginAgreeProtocolView *protocolView;

@end

@implementation HLLoginCodeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.loginPhoneKey = @"login_phone_key";
    _textField.text  = [[NSUserDefaults standardUserDefaults] stringForKey:_loginPhoneKey];
}

- (void)setupNavigationItems
{
    [super setupNavigationItems];
    self.title = @"";
}

- (void)initSubviews
{
    [super initSubviews];
    
    self.headerView = [[UIImageView alloc] initWithImage:UIImageMake(@"login_header")];
    [self.view addSubview:_headerView];
    [_headerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_equalTo(0);
    }];
    
    self.titleLabel = [[UILabel alloc] qmui_initWithFont:UIFontMediumMake(24) textColor:HLTextColor1];
    _titleLabel.text = @"手机号登录";
    [self.view addSubview:_titleLabel];
    [_titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(24);
        make.right.mas_equalTo(-24);
        make.top.mas_equalTo(NavigationContentTopConstant + 48);
    }];
    
    self.detailLabel = [[UILabel alloc] qmui_initWithFont:UIFontMake(14) textColor:HLTextColor2];
    _detailLabel.text = @"未注册过的手机号登录后将自动创建账号";
    _detailLabel.numberOfLines = 0;
    [self.view addSubview:_detailLabel];
    [_detailLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(_titleLabel);
        make.top.equalTo(_titleLabel.mas_bottom).offset(8);
    }];

    self.textField = [[QMUITextField alloc] init];
    _textField.placeholder = @"请输入手机号";
    _textField.font = UIFontMake(14);
    _textField.textColor = HLTextColor1;
    _textField.backgroundColor = UIColorWhite;
    _textField.layer.borderWidth = 2;
    _textField.layer.borderColor = HLLineColor.CGColor;
    _textField.layer.masksToBounds = YES;
    _textField.layer.cornerRadius = 12;
    _textField.maximumTextLength = 11;
    _textField.delegate = self;
    _textField.textInsets = UIEdgeInsetsMake(0, 16, 0, 16);
    _textField.keyboardType = UIKeyboardTypePhonePad;
    [self.view addSubview:_textField];
    [_textField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(_titleLabel);
        make.top.equalTo(_detailLabel.mas_bottom).offset(40);
        make.height.mas_equalTo(60);
    }];
    
    self.codeField = [[QMUITextField alloc] init];
    _codeField.placeholder = @"请输入验证码";
    _codeField.font = UIFontMake(14);
    _codeField.textColor = HLTextColor1;
    _codeField.backgroundColor = UIColorWhite;
    _codeField.textInsets = UIEdgeInsetsMake(0, 16, 0, 16);
    _codeField.maximumTextLength = 4;
    _codeField.layer.borderWidth = 2;
    _codeField.layer.borderColor = HLLineColor.CGColor;
    _codeField.layer.masksToBounds = YES;
    _codeField.layer.cornerRadius = 12;
    _codeField.keyboardType = UIKeyboardTypeNumberPad;
    _codeField.delegate = self;
    [self.view addSubview:_codeField];
    [_codeField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(_textField);
        make.top.equalTo(_textField.mas_bottom).offset(16);
        make.height.equalTo(_textField);
    }];
    
    self.codeButton = [[QMUIButton alloc] init];
    [_codeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
    [_codeButton setTitleColor:HLMainColor forState:UIControlStateNormal];
    [_codeButton.titleLabel setFont:UIFontMake(14)];
    [_codeButton setBackgroundColor:UIColorWhite];
    [_codeButton setContentEdgeInsets:UIEdgeInsetsMake(8, 8, 8, 8)];
    [_codeButton addTarget:self action:@selector(SMSButtonDidClicked:) forControlEvents:UIControlEventTouchUpInside];
    _codeButton.enabled = NO;
    [self.view addSubview:_codeButton];
    [_codeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(_codeField);
        make.right.equalTo(_codeField).offset(-16);
    }];
    
    
    self.saveButton = [[QMUIButton alloc] init];
    _saveButton.titleLabel.font = UIFontMake(15);
    [_saveButton setTitle:@"登录" forState:UIControlStateNormal];
    [_saveButton setTitleColor:UIColorWhite forState:UIControlStateNormal];
    [_saveButton setBackgroundColor:HLMainColor];
    _saveButton.cornerRadius = 12;
    _saveButton.enabled = NO;
    [_saveButton addTarget:self action:@selector(saveAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_saveButton];
    [_saveButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(_codeField);
        make.height.mas_equalTo(50);
        make.top.equalTo(_codeField.mas_bottom).offset(34);
    }];
    
    
    self.protocolView = [[HLLoginAgreeProtocolView alloc] init];
    _protocolView.agreeButton.selected = YES;
    [self.view addSubview:_protocolView];
    [_protocolView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(0);
        make.width.mas_lessThanOrEqualTo(SCREEN_WIDTH);
        make.bottom.mas_equalTo(-(SafeAreaInsetsConstantForDeviceWithNotch.bottom + 12));
    }];
}

- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleDarkContent;
}

- (UIImage *)qmui_navigationBarBackgroundImage
{
    return [UIImage qmui_imageWithColor:UIColorClear];
}

- (nullable UIColor *)qmui_navigationBarTintColor
{
    return UIColorBlack;
}

- (BOOL)shouldHideKeyboardWhenTouchInView:(UIView *)view
{
    return YES;
}

- (void)saveAction
{
    NSString *account = self.textField.text;
    NSString *code = self.codeField.text;
    
    if (account.length < 1){
        [QMUITips showWithText:@"请输入手机"];
        return;
    }
    
    if (code.length < 1){
        [QMUITips showWithText:@"请输入验证码"];
        return;
    }
    [[NSUserDefaults standardUserDefaults] setObject:account forKey:_loginPhoneKey];
    
    NSDictionary *params = @{
        @"mobile":account,
        @"code":code,
        @"loginType":@"0",// 0:手机; 1:邮箱; 2:一键登陆 3:游客
        @"countryCode":@"86"};
    [HLUIHelper loginWithParams:params];
}


- (void)SMSButtonDidClicked:(QMUIButton *)button
{
    NSString *account = [self.textField text];
    
    HLLoginOptionRequest *loginOptionRequest = [[HLLoginOptionRequest alloc] initWithType:HLLoginOptionTypeSendSmsCode params:@{@"countryCode":@"86", @"mobile":account,  @"scene":@"LOGIN"}];// 场景短信状态,可用值:LOGIN,FIND_PWD,BIND_MOBILE,MODIFY_PWD
    [loginOptionRequest startWithCompletionBlockWithSuccess:^(__kindof HLLoginOptionRequest * _Nonnull request) {
        if (request.isSuccess){
            [QMUITips showWithText:@"验证码已发送"];
            [self startCountdownTimerIfNecessary];
        } else {
            [QMUITips showWithText:request.message];
        }
    } failure:nil];

}

- (void)startCountdownTimerIfNecessary
{
    if (self.countdownTimer) {
        return;
    }
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(countdownTimerDidFire:) userInfo:nil repeats:YES];
    self.codeButton.enabled = NO;
    self.codeButton.tag = 60;
    [self.codeButton setTitle:@"60s后重发" forState:UIControlStateDisabled];
    self.countdownTimer = timer;
}

- (void)countdownTimerDidFire:(NSTimer *)sender
{
    NSInteger seconds = self.codeButton.tag - 1;
    [self.codeButton setTitle:[NSString stringWithFormat:@"%zds后重发",seconds] forState:UIControlStateDisabled];
    self.codeButton.tag = seconds;
    if (self.codeButton.tag == 0) {
        self.codeButton.enabled = YES;
        [self cancelCountdownTimer];
    }
}

- (void)cancelCountdownTimer
{
    [self.countdownTimer invalidate];
    self.countdownTimer = nil;
    self.codeField.enabled = YES;
    [self.codeButton setTitle:@"重新获取" forState:UIControlStateNormal];
}

#pragma QMUITextFieldDelegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string originalValue:(BOOL)originalValue
{
    self.codeButton.enabled = (self.textField.text.length >= 10);
    self.saveButton.enabled = (([self.textField.text length] >= 10) && ( [self.codeField.text length] >= 3));
    return YES;
}

@end
